<template>
  <div class="hr-interview-record-container">
    <div class="header">
      <h2>HR面试记录</h2>
      <div class="actions">
        <a-button type="primary" @click="addRecord">
          <template #icon>
            <plus-outlined />
          </template>
          新增面试
        </a-button>
      </div>
    </div>

    <a-card class="record-card">
      <a-table
        :columns="columns as any"
        :data-source="records"
        :pagination="pagination"
        row-key="id"
        :loading="loading"
        bordered
      >
        <!-- 自定义status表格列 -->
        <template #status="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ getStatusText(text) }}
          </a-tag>
        </template>

        <!-- 自定义时长列 -->
        <template #duration="{ text }">
          <span>{{ formatDuration(text) }}</span>
        </template>

        <!-- 自定义时间列 -->
        <template #time="{ text }">
          <span>{{ formatDate(text) }}</span>
        </template>

        <!-- 自定义action列 -->
        <template #action="{ record }">
          <a-button
            type="link"
            @click="viewAnalysis(record)"
            :disabled="record.interviewStatus !== 2"
          >
            查看分析
          </a-button>
          <a-popconfirm
            title="确定要删除此笔试记录吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="deleteRecord(record)"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>

    <!-- 无数据时的提示 -->
    <a-empty v-if="records.length === 0 && !loading" description="暂无面试记录" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  Card as ACard,
  Table as ATable,
  Button as AButton,
  Tag as ATag,
  Empty as AEmpty,
  message,
} from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { PlusOutlined } from '@ant-design/icons-vue'
import { deleteHrInterviewUsingGet, getHrInterviewListUsingGet } from '@/api/hrInterviewController'
import { formatDuration } from '@/utils/FormatTime'

const router = useRouter()
const loading = ref(true)

// 定义HR面试记录数据类型
interface HrInterviewRecord {
  id: string
  userId: string
  resumeId: string
  techField: string
  position: string
  company: string
  createTime: string
  duration: number
  interviewStatus: number
}

// 表格列定义
const columns = [
  {
    title: '岗位',
    dataIndex: 'position',
    key: 'position',
    width: 150,
    sorter: (a: HrInterviewRecord, b: HrInterviewRecord) => a.position.localeCompare(b.position),
  },
  {
    title: '公司',
    dataIndex: 'company',
    key: 'company',
    width: 150,
    sorter: (a: HrInterviewRecord, b: HrInterviewRecord) => a.company.localeCompare(b.company),
  },
  {
    title: '技术领域',
    dataIndex: 'techField',
    key: 'techField',
    width: 120,
  },
  {
    title: '面试时间',
    dataIndex: 'createTime',
    key: 'time',
    width: 160,
    slots: { customRender: 'time' },
    sorter: (a: HrInterviewRecord, b: HrInterviewRecord) =>
      new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
  },
  {
    title: '时长',
    dataIndex: 'interviewDuration',
    key: 'duration',
    width: 100,
    align: 'center',
    slots: { customRender: 'duration' },
    sorter: (a: HrInterviewRecord, b: HrInterviewRecord) => a.duration - b.duration,
  },
  {
    title: '状态',
    dataIndex: 'interviewStatus',
    key: 'status',
    width: 120,
    align: 'center',
    slots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
    slots: { customRender: 'action' },
  },
]

// 分页配置
const pagination = ref({
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['5', '10', '20', '50'],
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 面试记录数据
const records = ref<HrInterviewRecord[]>([])

/**
 * 获取状态标签颜色
 * @param {number} status 面试状态码
 * @returns {string} 颜色代码
 */
const getStatusColor = (status: number) => {
  const map: Record<number, string> = {
    0: 'orange', // 未完成
    1: 'blue', // 分析中
    2: 'green', // 已完成
  }
  return map[status] || 'gray'
}

/**
 * 获取状态文本
 * @param {number} status 面试状态码
 * @returns {string} 状态文本
 */
const getStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: '未完成',
    1: '分析中',
    2: '已完成',
  }
  return map[status] || '未知状态'
}

/**
 * 格式化日期
 * @param {string} dateString ISO日期字符串
 * @returns {string} 格式化后的日期字符串
 */
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
    .getDate()
    .toString()
    .padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date
    .getMinutes()
    .toString()
    .padStart(2, '0')}`
}

/**
 * 查看分析报告
 * @param record
 */
const viewAnalysis = (record: HrInterviewRecord) => {
  if (record.interviewStatus !== 2) {
    message.warning('面试分析尚未完成，无法查看')
    return
  }
  router.push({ path: '/api/hr/interview/analyze', query: { id: record.id } })
}

const addRecord = () => {
  message.info('新增面试功能待实现')
}

/**
 * 获取hr面试记录
 */
const fetchHrInterviewRecords = async () => {
  loading.value = true
  const res = await getHrInterviewListUsingGet()
  if (res.code === 0 && res.data) {
    records.value = res.data as any
  } else {
    message.error('获取HR面试记录失败: ' + res.message)
  }
  loading.value = false
}

/**
 * 删除hr面试记录
 * @param record
 */
const deleteRecord = async (record: HrInterviewRecord) => {
  const res = await deleteHrInterviewUsingGet({ hrInterviewId: record.id as any })
  if (res.code === 0) {
    message.success('删除面试记录成功')
    //重新加载数据
    await fetchHrInterviewRecords()
  } else {
    message.error('删除面试记录失败: ' + res.message)
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  // 获取数据
  await fetchHrInterviewRecords()
})
</script>

<style scoped>
.hr-interview-record-container {
  padding: 40px 0;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  font-size: 28px;
  color: #1890ff;
  font-weight: 700;
  letter-spacing: 2px;
  margin: 0;
}

.actions {
  display: flex;
  gap: 12px;
}

.record-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(24, 144, 255, 0.08);
  margin-bottom: 24px;
}

:deep(.ant-table) {
  border-radius: 8px;
  min-width: 900px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f0f7ff;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #e6f7ff !important;
}

:deep(.ant-btn-link[disabled]) {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}

:deep(.ant-table-row) {
  transition: all 0.3s;
}

:deep(.ant-tag) {
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 4px;
}

:deep(.ant-pagination) {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .hr-interview-record-container {
    padding: 20px 10px;
  }

  .header h2 {
    font-size: 22px;
  }
}
</style>
